package com.cyufeng.blog.service;

import com.cyufeng.blog.common.DFAtext;
import com.cyufeng.blog.common.SetCode;
import com.cyufeng.blog.dto.ArticleDto;
import com.cyufeng.blog.entity.Article;
import com.cyufeng.blog.entity.Review;
import com.cyufeng.blog.repository.ArticleRepository;
import com.cyufeng.blog.repository.ReviewRepository;
import com.cyufeng.blog.service.mapper.ArticleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 文章
 *
 * @author Cyufeng
 * Data:2019.01.05
 */
@Service
public class ArticleSerivce {
    @Autowired
    ArticleRepository articleRepository;

    @Autowired
    ReviewRepository reviewRepository;

    @Autowired
    SensitiveService sensitiveService;

    ArticleMapper articleMapper = new ArticleMapper();

    //    获得唯一标示给article的code字段
    SetCode setCode = new SetCode();

    //敏感词判断
    DFAtext dfAtext = new DFAtext();

    /**
     * 保存文章
     * @param articleDto
     * @return
     */
    public Map<String,Object> saveArticle(ArticleDto articleDto) {
        Map<String,Object> returnMap = new HashMap<>();
        try {
            //老师要求在这里加上一个敏感词判断
            Set<String> set = dfAtext.search(articleDto.getEditorial(),sensitiveService.getAllWord());
            if (set.size()>0){
                returnMap.put("message","error");
                returnMap.put("data",set);
                return returnMap;
//                System.out.println("语句中包含敏感词的个数为：" + set.size() + "。包含：" + set);
            }

//            将从前台传来的dto通过mapper转为entity再保存entity
            Article article = new Article();
            article = articleMapper.dtoToentity(articleDto);
            article.setMadeTime(new Date());
            article.setCode(setCode.setcode());
            articleRepository.save(article);
//            将新增的entity的id和title字段保存到审批表里面
            Review review = new Review();
            review.setArticleCode(article.getCode());//设置文章的唯一标示
            review.setArticleTitle(article.getTitle());//设置文章标题
            review.setIsEnable(0);//是否审批，这个字段会和文章表里面的字段同步
            review.setDr(0);//是否删除
            review.setMadeTime(new Date());//创建时间
            reviewRepository.save(review);
            returnMap.put("message","success");

            return returnMap;
        } catch (Exception e) {
            returnMap.put("message","error");
            return returnMap;
        }
    }


    /**
     * 分页查询文章，有条件--用于普通游客显示
     * @param pageNum
     * @param pageLimit
     * @return
     */
    public Map<String, Object> getArticle(Integer pageNum, Integer pageLimit,int sort) {
        Pageable pageable = new PageRequest(pageNum - 1, pageLimit);

        Page<Article> pp ;
        if (sort != 0 ){
            pp = articleRepository.getAllArticle(sort, pageable);
        }
        else {
            pp = articleRepository.getAllArticle(pageable);
        }

//        EntityToDto
        List<Article> articleList = pp.getContent();
        List<ArticleDto> articleDtoList = articleMapper.entityTodto(articleList);
        Map<String, Object> pageMap = new HashMap<>();
        pageMap.put("content", articleDtoList);//数据
        pageMap.put("totalPages", pp.getTotalPages());//一共有几页
        pageMap.put("totalElements", pp.getTotalElements());//一共有多少条数据
        pageMap.put("pageSize", pp.getPageable().getPageSize());//一页有几条数据
        pageMap.put("pageNumber", pp.getPageable().getPageNumber());//这是第几页
        return pageMap;
    }

    /**
     * 根据id查找文章--用于普通游客显示
     * @param articleId
     * @return
     */
    public ArticleDto getOneArticle(int articleId){
        Article article = articleRepository.findOneArticleById(articleId);
//        这里可以有一个是否为空的判断，但是现在还没有时间去弄后端调用前端提示的方法，以后有时间可以加上
        return articleMapper.entityTodto(article);
    }

    /**
     * 分页查询工具，有条件--用于普通游客显示
     * @param pageNum
     * @param pageLimit
     * @return
     */
    public Map<String, Object> getTool(Integer pageNum, Integer pageLimit) {
        Pageable pageable = new PageRequest(pageNum - 1, pageLimit);
        Page<Article> pp = articleRepository.getAllTool(1, pageable);
//        EntityToDto
        List<Article> toolList = pp.getContent();
        List<ArticleDto> toolDtoList = articleMapper.entityTodto(toolList);
        Map<String, Object> pageMap = new HashMap<>();
        pageMap.put("content", toolDtoList);//数据
        pageMap.put("totalPages", pp.getTotalPages());//一共有几页
        pageMap.put("totalElements", pp.getTotalElements());//一共有多少条数据
        pageMap.put("pageSize", pp.getPageable().getPageSize());//一页有几条数据
        pageMap.put("pageNumber", pp.getPageable().getPageNumber());//这是第几页
        return pageMap;
    }

    /**
     * 根据id查找文章--用于普通游客显示
     * @param toolId
     * @return
     */
    public ArticleDto getOneTool(int toolId){
        Article article = articleRepository.findOneToolById(toolId);
//        这里可以有一个是否为空的判断，但是现在还没有时间去弄后端调用前端提示的方法，以后有时间可以加上
        return articleMapper.entityTodto(article);
    }

    /**
     * 修改是否启用--用于后台操作
     * @param isEnable
     * @param id
     * @return
     */
    @Transactional
    public String setIsEnbale(Boolean isEnable, int id) {
        int tempIsEnable = 0;
        try {
            if (isEnable == true)
                tempIsEnable = 1;
            articleRepository.setIsEnable(tempIsEnable, id);
            return "success";
        } catch (Exception e) {
            return "error";
        }
    }


    /**
     * 分页查询文章，有条件-用于后台操作
     * @param pageNum
     * @param pageLimit
     * @return
     */
    public Map<String, Object> getAllArticle(Integer pageNum, Integer pageLimit,int sort) {
        Pageable pageable = new PageRequest(pageNum - 1, pageLimit);

        Page<Article> pp ;
        if (sort != 0 ){
            pp = articleRepository.getAllArticle_back(sort, pageable);
        }
        else {
            pp = articleRepository.getAllArticle_back(pageable);
        }

//        EntityToDto
        List<Article> articleList = pp.getContent();
        List<ArticleDto> articleDtoList = articleMapper.entityTodto(articleList);
        Map<String, Object> pageMap = new HashMap<>();
        pageMap.put("content", articleDtoList);//数据
        pageMap.put("totalPages", pp.getTotalPages());//一共有几页
        pageMap.put("totalElements", pp.getTotalElements());//一共有多少条数据
        pageMap.put("pageSize", pp.getPageable().getPageSize());//一页有几条数据
        pageMap.put("pageNumber", pp.getPageable().getPageNumber());//这是第几页
        return pageMap;
    }
    //    删除用户
    @Transactional
    public String deleteArticle(int id) {
        try {
            articleRepository.deleteArticle(id);
            return "success";
        } catch (Exception e) {
            return "error";
        }
    }

    /**
     * 分页查询工具，有条件--用于后台管理
     * @param pageNum
     * @param pageLimit
     * @return
     */
    public Map<String, Object> getAllTool(Integer pageNum, Integer pageLimit) {
        Pageable pageable = new PageRequest(pageNum - 1, pageLimit);
        Page<Article> pp = articleRepository.getAllTool_back(1, pageable);
//        EntityToDto
        List<Article> toolList = pp.getContent();
        List<ArticleDto> toolDtoList = articleMapper.entityTodto(toolList);
        Map<String, Object> pageMap = new HashMap<>();
        pageMap.put("content", toolDtoList);//数据
        pageMap.put("totalPages", pp.getTotalPages());//一共有几页
        pageMap.put("totalElements", pp.getTotalElements());//一共有多少条数据
        pageMap.put("pageSize", pp.getPageable().getPageSize());//一页有几条数据
        pageMap.put("pageNumber", pp.getPageable().getPageNumber());//这是第几页
        return pageMap;
    }

}
